package com.example.demo.controller;

import com.example.demo.constant.Constant;
import com.example.demo.model.UserInfo;
import com.example.demo.service.UserInfoService;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserInfoService userInfoService;
    @RequestMapping("/login")
    public Boolean login(String userName, String password, HttpSession session){
        if(!StringUtils.hasText(userName) || !StringUtils.hasText(password)){
            return false;
        }

//根据用户名获取信息
        UserInfo userInfo=userInfoService.queryUserInfoByName(userName);
        if(userInfo==null){
            return false;
        }
        if(password.equals(userInfo.getUPassword())){
            session.setAttribute(Constant.SESSION_USER_KEY,userInfo);
            return true;
        }
        return false;
    }


    @RequestMapping("/register")
    public boolean register(UserInfo userInfo){
        log.info("添加用户，request:"+userInfo);
        if(!StringUtils.hasLength(userInfo.getUId())
                ||!StringUtils.hasLength(userInfo.getUName())
                ||userInfo.getUPassword()==null
                ||userInfo.getUSex()==null
                ||userInfo.getUEmail()==null
        ){
            log.info("添加用户，参数不合法，request："+userInfo);
            return false;
        }
        try {
            userInfoService.register(userInfo);
            return true;
        }catch (Exception e){
            log.info("添加用户异常，e："+e);
            return false;
        }
    }

}


